package com.ts.api.module.channel.service.impl;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.constant.channel.ChannelRegisterFieldEnum;
import com.ts.api.common.context.ChannelRequestContext;
import com.ts.api.exp.BizException;
import com.ts.api.module.channel.dao.ChannelRegisterFieldDao;
import com.ts.api.module.channel.entity.ChannelRegisterField;
import com.ts.api.module.channel.entity.vo.ReqChannelRegisterFieldVO;
import com.ts.api.module.channel.service.ChannelRegisterFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 动态注册字段实现类
 * @Author: ghb
 * @Date: 2023/9/21 14:35
 */
@Service
public class ChannelRegisterFieldServiceImpl implements ChannelRegisterFieldService {

    @Autowired
    private ChannelRegisterFieldDao registerFieldDao;

    /**获取动态表单字段值列表*/
    @Override
    public List<ChannelRegisterField> list(Long channelId) {
        List<ChannelRegisterField> list = registerFieldDao.list(channelId);

        String getTableFlow = ChannelRequestContext.getTableFlow();

        //  前置流程
        if ("1".equals(getTableFlow)) {
            CollUtils.filter(list, t -> Eq.strOr(t.getMappingName(), ChannelRegisterFieldEnum.USER_NAME.getMappingName(), ChannelRegisterFieldEnum.IDCARD.getMappingName()));
        }
        //  后置流程
        if ("2".equals(getTableFlow)) {
            CollUtils.filter(list, t -> Eq.strOr(t.getMappingName(), ChannelRegisterFieldEnum.PHONE.getMappingName()));
        }
        return list;
    }

    @Override
    public void checkFieldParam(List<ReqChannelRegisterFieldVO> listReqChannelRegisterFieldVO, List<ChannelRegisterField> listChannelRegisterField) {

        List<ChannelRegisterField> find = CollUtils.find(listChannelRegisterField, t -> Eq.strOr(t.getMappingName(), ChannelRegisterFieldEnum.USER_NAME.getMappingName(), ChannelRegisterFieldEnum.IDCARD.getMappingName()));
        List<Long> ids = CollUtils.toList(find, t -> t.getId());
        CollUtils.filter(listChannelRegisterField, t -> ids.contains(t.getId()));

        if (listReqChannelRegisterFieldVO.size() != listChannelRegisterField.size()) {
            BizException.fastFail(BizEnum.REGISTER_PARAM_SIZE);
        }

        //  校验id
        for (ChannelRegisterField registerField: listChannelRegisterField) {
            Long fieldId = registerField.getId();
            if (!listReqChannelRegisterFieldVO.stream().filter(t -> t.getId().equals(fieldId)).findFirst().isPresent()) {
                BizException.fastFail(BizEnum.REGISTER_PARAM_ID);
            }
        }
        //  正则校验是否输入的正确
    }
}
